package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 权限认证：用户是否已经登录，是否拥有合法令牌
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 执行controller方法之前需要拦截，校验token
     *
     * @param request  current HTTP request
     * @param response current HTTP response
     * @param handler  chosen handler to execute, for type and/or instance evaluation
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求令牌，从请求头获取
        String token = request.getHeader("access_token");
        if (!StringUtils.hasText(token)) {
            throw new LeaseException(ResultCodeEnum.TOKEN_INVALID);
        } else {
            //解析令牌
            Claims claims = JwtUtil.parseToken(token);
            Long userId = claims.get("userId", Long.class);
            String username = claims.get("username", String.class);
            //如何将数据绑定到线程上，共享给controller使用。  --  ThreadLocal
            LoginUser loginUser = new LoginUser();
            loginUser.setUserId(userId);
            loginUser.setUsername(username);
            LoginUserContext.setLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理线程上绑定的数据。
        LoginUserContext.clear();
    }
}
